// pages/productDetails/productDetails.js
import {
  productApi,
  couponsApi,
  receiveApi,
  cartaddApi,
  cartcountApi,
  delApi,
  collectaddApi
} from '../../http/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: "",
    number: { //商品参数
      latitude: '',
      longitude: ''
    },
    image: {},
    run: '',
    storinf: '', //门店信息
    evaluation: { //评价参数
      page: 1,
      limit: 8,
      type: 0
    },
    goodreply: '', //好评率
    sumCount: '',
    information: {},
    pics: [], //评价图片
    piclist: [],
    isShow: 'hide',
    IsShow: 'hide',
    goodsid: '',
    list: [], //优惠劵
    replyChance: '', //详情页好评率
    reply: '', //评价
    merchantReplyContent: '', //店员回复
    merchantReply: false,
    chooseData: [],
    arres: '',
    data: {}, //商品详情
    productValue: {}, //选择商品条件
    goodsParametric: {},
    num: 1,
    storeInfo: {}, //商品头部详情
    count: '', //购物车数量
    userCollect: false, //收藏
  },

  /**
   * 生命周期函数--监听页面加载
   */
  // 循环判断商品详情
  goodsFor() {
    let _self = this
    let chooseData = _self.data.data.productAttr
    console.log(chooseData);
    let arr = []
    for (let i = 0; i < chooseData.length; i++) {
      var namdl = chooseData[i]
      for (let j = 0; j < namdl.attrValue.length; j++) {
        var obj = namdl.attrValue[j].check
        if (obj) {
          arr.push(namdl.attrValue[j].attr)
          if (arr.length == 2) {
            if (arr[0] == '90m') {
              arr.push(arr[0])
              arr.shift()
            }
          }
        }
      }
    }
    setTimeout(() => {
      let arres = String(arr)
      console.log(arres);
      let goodsParametric = _self.data.productValue[`${arres}`];
      console.log(goodsParametric);
      _self.setData({
        arres,
        goodsParametric,
      })
    }, 100)
  },
  // 商品数量判断
  initial() {
    setTimeout(() => {
      let _self = this
      let goodsNum = _self.data.goodsParametric.stock;
      let mixNum = _self.data.num
      console.log(mixNum, goodsNum);
      if (goodsNum == 0) {
        _self.setData({
          num: 0
        })
      } else {
        _self.setData({
          num: 1
        })
      }
    }, 200)
  },
  onLoad(options) {
    let url = '/' + options.id
    let _self = this
    console.log(url);
    // 商品详情
    productApi(this.data.number, url).then(res => {
      console.log(res);
      let data = res.data
      // 商品图
      let pic = data.storeInfo
      let piclist = pic.sliderImageArr
      // 运费
      let run = data.tempName
      // 规格
      let storeInfo = data.storeInfo
      console.log(storeInfo);
      let productValue = data.productValue
      let chooseData = data.productAttr
      console.log(chooseData);
      chooseData.map(item => {
        item.attrValue[0].check = true
      })
      let storinf = data.systemStore
      // 用户评价
      let reply = data.reply
      console.log(reply);
      // 好评率
      let replyChance = data.replyChance
      let pics = reply.picturesArr
      let sumCount = data.replyCount
      console.log(replyChance);
      // 店员回复
      let merchantReplyContent = reply.merchantReplyContent
      _self.setData({
        image: pic,
        run,
        storinf,
        piclist,
        reply,
        replyChance,
        pics,
        sumCount,
        merchantReplyContent,
        chooseData,
        data,
        productValue,
        storeInfo
      })
      console.log(merchantReplyContent);
      if (merchantReplyContent) {
        _self.setData({
          merchantReply: true
        })
      }
      _self.goodsFor()
      _self.initial()
    })
    //优惠券
    couponsApi({
      page: 1,
      limit: 20
    }).then(res => {
      console.log(res);
      let data = res.data
      _self.setData({
        list: data
      })
    })
    // 购物车数量
    cartcountApi({
      numType: 0
    }).then(res => {
      console.log(res);
      let count = res.data.count
      _self.setData({
        count
      })
    })
  },
  //跳转门店列表
  toaddresslist(e) {
    wx.navigateTo({
      url: '../productDetails/addresslist/addresslist',
    })
  },
  // 跳评价列表
  toevaluatelist(e) {
    console.log(e);
    let goodsid = e.currentTarget.dataset.goodsid
    wx.navigateTo({
      url: '../productDetails/evaluatelist/evaluatelist?id=' + goodsid,
    })
  },
  toHome() {
    wx.switchTab({
      url: '../index/index',
    })
  },
  //收藏
  collect(e) {
    let _self = this
    let id = e.currentTarget.dataset.goodsid
    collectaddApi({
      id: id,
      category: "collect"
    }).then(res => {
      console.log(res);
    })
    let url = '/' + id
    console.log(url);
    // 商品详情
    productApi(this.data.number, url).then(res => {
      console.log(res);
      let pic = res.data.storeInfo
      console.log(pic);
      _self.data.userCollect = true
      _self.setData({
        userCollect: _self.data.userCollect
      })
    })
  },
  //取消收藏
  delcollect(e) {
    let _self = this
    let id = e.currentTarget.dataset.goodsid
    delApi({
      id: id,
      category: "collect"
    }).then(res => {
      console.log(res);
    })

    console.log(id);
    let url = '/' + id
    console.log(url);
    // 商品详情
    productApi(_self.data.number, url).then(res => {
      console.log(res);
      let pic = res.data.storeInfo
      console.log(pic);
      _self.data.userCollect = false
      _self.setData({
        userCollect: _self.data.userCollect
      })
    })
  },
  toCar() {
    wx.switchTab({
      url: '../carts/carts',
    })
  },
  // 点击图片放大
  toshow(e) {
    console.log(e);
    let id = e.currentTarget.dataset.id
    let url = e.currentTarget.dataset.url
    console.log(url);
    console.log(id);
    let _self = this
    wx.previewImage({
      current: url,
      urls: _self.data.piclist
    })
  },

  // 规格显示遮罩层
  showModal: function (e) {
    console.log();
    let _self = this;
    _self.data.isShow = "show";
    // 创建动画
    let animation = wx.createAnimation({
      // 时间
      duration: 200,
      // 动画效果
      timingFunction: 'ease-in-out',
    })
    console.log(_self);
    // 给小程序对象添加一个动画属性=创建动画的实例
    _self.animation = animation;
    // 动画怎么动（浅拷贝）
    // y轴上为负的，y轴下为负 
    // step停止
      animation.translateY(-800).step();
      _self.setData({
        isShow: _self.data.isShow,
        // export导出动画
        animationData: _self.animation.export()
      })

      let chooseData = this.data.data.productAttr
      if (!this.data.choseFlag) {
        console.log(chooseData);
        chooseData.map(item => {
          item.attrValue[0].check = true
        })
      }
      this.setData({
        chooseData
      })
  },
  // 选择规格
  //选择商品
  backred(e) {
    this.setData({
      choseFlag: true
    })
    let _self = this
    console.log(e);
    let i = e.currentTarget.dataset.a
    let b = e.currentTarget.dataset.b
    console.log(i, b);
    _self.data.chooseData.map(item => {
      if (item.attrName == b) {
        let iten = item
        console.log(iten);
        item.attrValue[0].check = !item.attrValue[0].check
        item.attrValue[1].check = !item.attrValue[1].check
      }
    })
    _self.goodsFor()
    _self.setData({
      chooseData: _self.data.chooseData
    })
    _self.initial()

  },
  // 商品减
  removeGoods() {
    let _self = this
    if (_self.data.num <= 1) {
      return wx.showToast({
        title: '不能再减啦！',
        icon: 'error'
      })
    } else {
      _self.setData({
        num: --_self.data.num
      })
    }
  },
  // 商品加
  addGoods() {
    let _self = this
    let goodsNum = _self.data.goodsParametric.stock;
    if (_self.data.num >= goodsNum) {
      return wx.showToast({
        title: '超过商品库存!',
        icon: 'error'
      })
    } else {
      _self.setData({
        num: ++_self.data.num
      })
    }
  },
  //输入框数量判断 
  numberJudge(e) {
    let _self = this
    let inputNum = e.detail.value
    let goodsNum = _self.data.goodsParametric.stock;
    console.log(goodsNum);
    if (inputNum > goodsNum) {
      wx.showToast({
        title: '超过商品库存',
        icon: 'error'
      })
      _self.setData({
        num: goodsNum
      })
    }
  },
  // 收起弹窗
  popUp() {
    let _self = this;
    _self.animation.translateY(800).step();
    _self.data.isShow = "hide";
    _self.setData({
      // export导出动画
      animationData: _self.animation.export(),
      isShow: _self.data.isShow,
    })


  },
  // 优惠券显示遮罩层
  showcoupon() {
    let _self = this;
    _self.data.IsShow = "show";
    // 创建动画
    let animation = wx.createAnimation({
      // 时间
      duration: 200,
      // 动画效果
      timingFunction: 'ease-in-out',
    })
    console.log(_self);
    // 给小程序对象添加一个动画属性=创建动画的实例
    _self.animation = animation;
    // 动画怎么动（浅拷贝）
    // y轴上为负的，y轴下为负 
    // step停止
    animation.translateY(-800).step();
    _self.setData({
      IsShow: _self.data.IsShow,
      // export导出动画
      AnimationData: _self.animation.export()
    })
    couponsApi({
      page: 1,
      limit: 20
    }).then(res => {
      console.log(res);
      let data = res.data
      _self.setData({
        list: data
      })
    })
  },
  Popup() {
    let _self = this;
    _self.animation.translateY(800).step();
    _self.data.IsShow = "hide";
    _self.setData({
      // export导出动画
      AnimationData: _self.animation.export(),
      IsShow: _self.data.IsShow
    })
  },
  //领取优惠劵e
  draw(e) {
    let _seif = this
    let id = e.currentTarget.dataset.couponid
    console.log(id);
    let ree = {
      couponId: id
    }
    receiveApi(ree).then(res1 => {
      console.log(res1);
      couponsApi({
        page: 1,
        limit: 8
      }).then(res => {
        console.log(res);
        var list = res.data
        _seif.setData({
          list
        })
      })
    })
  },
  
  // 跳地图页面
  tomap(e) {
    console.log(e);
    let info = e.currentTarget.dataset.info.systemStore
    console.log(info);
    wx.setStorageSync('message', info)
    wx.navigateTo({
      url: '../productDetails/map/map',
    })
  },
  // 加入购物车
  tocart() {
    let _self = this
    console.log(_self.data);
    let obj = _self.data.productValue
    console.log(obj);
    let arres = _self.data.arres
    console.log(arres);
    let productId = obj[arres].productId
    console.log(productId);
    let uniqueId = obj[arres].unique
    console.log(uniqueId)
    console.log(_self.data.num);
    cartaddApi({
      cartNum: _self.data.num,
      new: 0,
      productId:productId,
      uniqueId:uniqueId
    }).then(res => {
      console.log(res);
    })
    cartcountApi({
      numType: 0
    }).then(res => {
      console.log(res);
      let count = res.data.count
      if (count < _self.data.goodsParametric.stock) {
        count = count + _self.data.num
      } else {
        wx.showToast({
          title: '超过商品库存',
          icon: 'error'
        })
      }
      _self.setData({
        count
      })
    })
    _self.popUp()
  },
  // 跳订单页面
  toorder() {
    let _self = this
    let obj = _self.data.productValue
    console.log(obj);
    let arres = _self.data.arres
    console.log(arres);
    let productId = JSON.stringify(obj[arres].productId)
    let uniqueId = obj[arres].unique
    console.log(_self.data.num,productId,uniqueId);
      cartaddApi({
        cartNum: _self.data.num,
        new:1,
        productId:productId,
        uniqueId:uniqueId
        }).then(res => {
          console.log(res);
          wx.navigateTo({
            url: './payment/payment?cartId='+res.data.cartId,
          })
        })
    },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})